<template>
	<div class="system-role-container layout-padding">
		<div class="system-role-padding layout-padding-auto layout-padding-view">
			<div class="system-user-search">
				<el-input size="default" class="w_150 mb15 mr10" v-model="listQuery.Name" placeholder="策略名" @keydown.enter="searchForm"> </el-input>

				<el-button size="default" @click="searchForm" type="primary" class="mr10 mb15"> 查询 </el-button>
				<el-button size="default" type="success" class="mr10 mb15" @click="addRule"> 新增 </el-button>
				<el-button size="default" type="info" class="mr10 mb15" @click="resetForm"> 重置 </el-button>
			</div>
			<tableTem ref="tableRef" v-bind:="state.tableData" @pageChange="onTablePageChange">
				<el-table-column align="center" type="index" label="序号" width="60" />
				<el-table-column align="center" min-width="120" prop="activationName" label="策略名"></el-table-column>
				<el-table-column align="center" prop="remark" min-width="150" label="备注"></el-table-column>
				<el-table-column align="center" prop="wariningValue" min-width="120" label="警戒值"></el-table-column>
				<el-table-column align="center" prop="refuseValue" min-width="120" label="拒绝值"></el-table-column>
				<el-table-column label="操作" align="center" width="160" fixed="right">
					<template #default="scope">
						<el-button size="small" type="primary" text @click="editOption(scope.row, 1)">编辑</el-button>
						<el-button size="small" type="primary" text @click="editOption(scope.row, 2)">复制</el-button>
						<el-button size="small" type="primary" text @click="getRule(scope.row)">管理规则</el-button>
						<el-button size="small" type="primary" text @click="onRowDel(scope.row.id)">删除</el-button>
						<el-switch
							class="ml10"
							size="small"
							:disabled="state.riskLoad == true"
							@change="handleChange(scope.row.status, scope.row.id)"
							v-model="scope.row.status"
							:inactive-value="0"
							:active-value="1"
						>
						</el-switch>
					</template>
				</el-table-column>
			</tableTem>
		</div>
		<!-- 弹窗 -->
		<el-dialog
			:title="state.dialogTitle"
			v-model="state.dialogVisible"
			:close-on-click-modal="false"
			:show-close="false"
			:close-on-press-escape="false"
			width="500px"
		>
			<el-form class="dialog-layout" ref="userForm" :rules="rules" :model="state.ruleForm" size="default" label-width="100px">
				<el-row :gutter="35">
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20" prop>
						<el-form-item label="策略名" prop="activationName">
							<div class="flex-c-c">
								<el-input v-model="state.ruleForm.activationName" class="w_250 mr10" placeholder="请输入策略名" clearable></el-input>
								<el-tooltip class="item" effect="dark" content="显示名称，一般为中文，如'异常注册'" placement="right-end">
									<el-icon size="25px" color="#409eff">
										<ele-QuestionFilled />
									</el-icon>
								</el-tooltip>
							</div>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20" prop>
						<el-form-item label="备注">
							<el-input v-model="state.ruleForm.remark" class="w_250 mr10" placeholder="请输入备注" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="警戒值" prop="wariningValue">
							<div class="flex-c-c">
								<el-input v-model="state.ruleForm.wariningValue" class="w_250 mr10" placeholder="请输入警戒值" clearable></el-input>
								<el-tooltip class="item" effect="dark" content="如果实际风险分数大于此数字，此交易则需要人工审核" placement="right-end">
									<el-icon size="25px" color="#409eff">
										<ele-QuestionFilled />
									</el-icon>
								</el-tooltip>
							</div>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20" prop>
						<el-form-item label="拒绝值" prop="refuseValue">
							<div class="flex-c-c">
								<el-input v-model="state.ruleForm.refuseValue" class="w_250 mr10" placeholder="请输入拒绝值" clearable></el-input>
								<el-tooltip class="item" effect="dark" content="如果实际风险分数大于此数字，此交易则直接拒绝" placement="right-end">
									<el-icon size="25px" color="#409eff">
										<ele-QuestionFilled />
									</el-icon>
								</el-tooltip>
							</div>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<div class="dialog-btn">
				<el-button @click="onCancel" size="default">取 消</el-button>
				<el-button type="primary" @click="onSubmit(userForm)" size="default">确 认</el-button>
			</div>
		</el-dialog>
		<ruleTem @refresh="resetForm()" ref="ruleTemFef" />
	</div>
</template>

<script setup lang="ts">
import { defineAsyncComponent, reactive, onMounted, ref } from 'vue';
import { ElMessageBox, ElMessage, FormInstance } from 'element-plus';
import {
	RiskActivationGetPagedList,
	RiskActivationDelete,
	RiskActivationCreate,
	RiskActivationUpdate,
	RiskActivationCopy,
	SetRiskActivationStatus,
} from '/@/api/model/index';

// 引入组件
const ruleTem = defineAsyncComponent(() => import('./ruleTem.vue'));
const tableTem = defineAsyncComponent(() => import('/@/components/tables/index.vue'));
// 定义父组件传过来的值
const props = defineProps({
	modelId: {
		type: [Number, String],
		default: () => '',
	},
});
// 定义变量内容
const ruleTemFef = ref();
const tableRef = ref();
const listQuery = reactive({
	Name: '', //名称
});
const state = reactive<any>({
	tableData: {
		data: [],
		total: 0,
		loading: true,
		param: {
			PageIndex: 1,
			PageSize: 10,
		},
	},
	ruleForm: {
		activationName: '',
		wariningValue: '',
		refuseValue: '',
		remark: '',
		id: '',
		status: '',
	} as any, // 新增
	dialogVisible: false, // 弹窗状态
	dialogTitle: '', //弹窗标题
	riskLoad: false, // 设置风控规则状态
	isEdit: false, //是否编辑
});
// 页面加载时
onMounted(() => {
	getTableData();
});

// 初始化表格数据
const getTableData = async () => {
	state.tableData.loading = true;
	try {
		const params = {
			...state.tableData.param,
			...listQuery,
			modelId: props.modelId,
		};
		Object.keys(params).forEach((key) => {
			if (!params[key]) delete params[key];
		});
		let data = await RiskActivationGetPagedList(params);
		state.tableData.data = data.data.items;
		state.tableData.total = data.data.totalCount;
	} finally {
		state.tableData.loading = false;
	}
};

// 新增
const addRule = () => {
	state.ruleForm.activationName = '';
	state.ruleForm.wariningValue = '';
	state.ruleForm.refuseValue = '';
	state.ruleForm.remark = '';
	state.dialogVisible = true;
	state.isEdit = false;
	state.dialogTitle = '新增策略';
};
// 编辑
const editOption = (item: any, type: any) => {
	state.ruleForm.activationName = item.activationName;
	state.ruleForm.wariningValue = item.wariningValue;
	state.ruleForm.refuseValue = item.refuseValue;
	state.ruleForm.remark = item.remark;
	state.ruleForm.status = item.status;
	state.dialogVisible = true;
	state.ruleForm.id = item.id;

	if (type == 1) {
		state.isEdit = true;
		state.dialogTitle = '编辑策略';
	} else {
		state.dialogTitle = '复制策略';
		state.ruleForm.activationName = '';
	}
};

// 删除账户
const onRowDel = (id: any) => {
	ElMessageBox.confirm(`此操作将永久删除策略信息，是否继续?`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
	}).then(async () => {
		await RiskActivationDelete([id]);
		ElMessage.success('删除成功');
		getTableData();
	});
};
// 分页改变
const onTablePageChange = (val: any) => {
	state.tableData.param.PageIndex = val.pageNum;
	state.tableData.param.PageSize = val.pageSize;
	getTableData();
};
// 搜索点击时表单回调
const searchForm = () => {
	state.tableData.param.PageIndex = 1;
	tableRef.value.pageReset();
};
// 重置
const resetForm = () => {
	listQuery.Name = '';
	searchForm();
};

// 关闭弹窗
const onCancel = () => {
	state.dialogVisible = false;
};

// 修改状态

const handleChange = async (v: any, id: any) => {
	state.tableData.riskLoad = true;
	try {
		await SetRiskActivationStatus({ status: v }, id);
		state.tableData.riskLoad = false;
		resetForm();
	} finally {
		state.tableData.riskLoad = false;
	}
};
const requiredNumber = (rule: any, value: any, callback: any) => {
	if (!value) {
		console.log(rule);
		callback(new Error(rule.fullField == 'wariningValue' ? '请输入警戒值' : '请输入拒绝值'));
	} else {
		if (!/^[+]?(\d+(\.\d+)?)?$/.test(value)) {
			callback(new Error('请输入数字'));
		} else {
			callback();
		}
	}
};
const rules = reactive({
	activationName: [{ required: true, message: '请输入策略名', trigger: ['blur', 'change'] }],
	wariningValue: [{ required: true, validator: requiredNumber, trigger: ['blur', 'change'] }],
	refuseValue: [{ required: true, validator: requiredNumber, trigger: ['blur', 'change'] }],
});
const userForm = ref<FormInstance>();
const onSubmit = async (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	await formEl.validate(async (valid) => {
		if (valid) {
			const params = {
				...state.ruleForm,
				modelId: props.modelId,
			};
			if (state.isEdit) {
				await RiskActivationUpdate(params, state.ruleForm.id);
			} else {
				delete params.status;

				if (state.dialogTitle === '复制策略') {
					await RiskActivationCopy(params, state.ruleForm.id);
				} else {
					console.log(11133333);
					delete params.id;

					await RiskActivationCreate(params);
				}
			}
			ElMessage.success(state.isEdit ? '修改成功' : '新增成功');
			onCancel();
			resetForm();
		}
	});
};
// 管理规则
const getRule = (item: any) => {
	ruleTemFef.value.openDialog(item);
};
</script>

<style scoped lang="scss">
.system-role-container {
	.system-role-padding {
		padding: 15px;
		.el-table {
			flex: 1;
		}
	}
}
.layout-padding {
	padding: 0 15px 15px 15px !important;
	width: 100%;
}
</style>
